package com.zrrd.sort;

import java.util.Arrays;

public class HeapSort {
    //1.调整为大根堆 不需要代码 最后根顶（n/2-1）左孩子：2n+1 右孩子： 2n+2
    public void heapSort(int[] array) {
        //2.调整为大根堆结构 一定要看一眼0节点
        for (int i = array.length / 2 - 1; i >= 0; i--) {
            buildHeap(array, i, array.length - 1);
        }
        //3.堆顶和堆底交换并弹出
        int temp;
        for (int i = array.length - 1; i >= 0; i--) {
            temp = array[i];
            array[i] = array[0];
            array[0] = temp;
            buildHeap(array, 0, i - 1);
        }
    }

    private void buildHeap(int[] array, int start, int end) {
        int temp;
        int child;
        for (int i = start; i * 2 + 1 <= end; i = child) {
            child = i * 2 + 2 <= end && array[2 * i + 2] > array[2 * i + 1] ? 2 * i + 2 : 2 * i + 1;
            if (array[i] < array[child]) {
                temp = array[i];
                array[i] = array[child];
                array[child] = temp;
            } else {
                break;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[]{4, 6, 7, 3, 2, 9, 1, 0, 5, 8};
        HeapSort hs = new HeapSort();
        hs.heapSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
